/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.api.entity.uri.AbstractURI;
import com.inspur.edp.lcm.metadata.api.entity.uri.MetadataURI;
import com.inspur.edp.lcm.metadata.api.exception.ErrorCodes;
import com.inspur.edp.lcm.metadata.api.exception.LcmMetadataDevException;
import com.inspur.edp.lcm.metadata.api.exception.MetadataNotFoundException;
import com.inspur.edp.lcm.metadata.cache.MdProjFileLastChangedCache;
import com.inspur.edp.lcm.metadata.core.entity.MdProjectDependencyNode;
import com.inspur.edp.lcm.metadata.core.exception.MetadataExceptionHandler;
import com.inspur.edp.lcm.metadata.core.index.ProjectMetadataCacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.util.Pair;

import java.util.Optional;

/**
 * @author zhaoleitr
 */
@Slf4j
public class RefCommonCoreService {
    private final MetadataProjectCoreService projectService = new MetadataProjectCoreService();

    private GspMetadata getRefMetadata(String metadataId, String projectPath, MetadataProject metadataProject) {
        // 初始化缓存
        ProjectMetadataCacheService projectMetadataCacheService = ProjectMetadataCacheService.getNewInstance(metadataProject, projectPath);
        //缓存中获取元数据归属并构造元数据
        return projectMetadataCacheService.getRefMetadata(metadataId);
    }

    public GspMetadata getRefMetadata(MetadataURI targetURI, AbstractURI sourceURI, String absolutePath) {
        Pair<Optional<GspMetadata>, Optional<MdProjectDependencyNode>> refMetadataAndSource = getRefMetadataAndSource(targetURI, sourceURI, absolutePath);
        if(refMetadataAndSource == null || !refMetadataAndSource.getFirst().isPresent()){
            return null;
        }
        return refMetadataAndSource.getFirst().get();
    }

    /**
     * 获取元数据及来源
     * @param targetURI
     * @param sourceURI
     * @param absolutePath
     * @return
     */
    public Pair<Optional<GspMetadata>, Optional<MdProjectDependencyNode>> getRefMetadataAndSource(MetadataURI targetURI, AbstractURI sourceURI, String absolutePath) {
        // 工程信息
        String projectPath = projectService.getProjPath(absolutePath);
        if (StringUtils.isBlank(projectPath)) {
            throw new LcmMetadataDevException(ErrorCodes.ECP_METADATA_DEV_0045, absolutePath);
        }
        MetadataProject metadataProject = projectService.getMetadataProjInfo(projectPath);

        // 初始化缓存
        ProjectMetadataCacheService projectMetadataCacheService = ProjectMetadataCacheService.getNewInstance(metadataProject, projectPath);
        try {
            return projectMetadataCacheService.getRefMetadataAndSource(targetURI.getId());
        } catch (MetadataNotFoundException ignore) {
            // 若查找不到依赖元数据, 则清理依赖引用关系图缓存后重新获取
            MdProjFileLastChangedCache.evict(projectPath);
            try {
                // 若清理缓存后仍获取不到,则抛出异常
                return projectMetadataCacheService.getRefMetadataAndSource(targetURI.getId());
            } catch (MetadataNotFoundException e) {
                MetadataExceptionHandler.handleMetadataNotFoundException(targetURI, sourceURI, projectPath);
            }
        }
        return null;
    }
}
